<template>
  <div
    class="lottery hideScrollBar"
    :class="{ 'lottery-fri': lotteryStore.isFri }"
    ref="scrollEl"
  >
    <!-- 背景图片 -->
    <div
      class="lottery-bg"
      :class="{
        'lottery-bg-end':
          lotteryStore.activityCurStatus == 3 ||
          lotteryStore.activityCurStatus == 5,
        'lottery-bg-fri': lotteryStore.isFri,
      }"
    />
    <!-- 导航 -->
    <NavBar
      isFixed
      :title="$t('lotteryMoney.cjxq')"
      isTransparent
      :navScorllOffset="60"
      navScorllColor="#fff"
      :scrollEl="scrollEl"
      :customBackFn="handleBack"
    />
    <!-- 骨架屏 -->
    <template v-if="!lottery">
      <van-skeleton title :row="3" style="margin-top: 25px" />
      <van-skeleton style="margin-top: 25px">
        <template #template>
          <div :style="{ display: 'flex', width: '100%' }">
            <van-skeleton-image />
            <div :style="{ flex: 1, marginLeft: '16px' }">
              <van-skeleton-paragraph row-width="60%" />
              <van-skeleton-paragraph />
              <van-skeleton-paragraph />
            </div>
          </div>
        </template>
      </van-skeleton>
    </template>
    <!-- 内容 -->
    <template v-else>
      <!-- 活动 -->
      <div class="content">
        <!-- 兑奖 -->
        <img
          v-if="!lotteryStore.isFri"
          class="lottery-redemption items-center"
          @click="jumpPage('bdcToMoney')"
          src="/image/lottery-v3/redemption-icon.svg"
        />
        <img
          v-else
          class="lottery-redemption items-center"
          @click="jumpPage('bdcToMoney')"
          src="/image/lottery-v3/redemption1-icon.svg"
        />
        <!-- 活动说明 -->
        <img
          v-if="!lotteryStore.isFri"
          class="lottery-desc"
          @click="jumpPage('lotteryDesc')"
          src="/image/lottery-v3/desc-icon.svg"
        />
        <img
          v-else
          class="lottery-desc"
          @click="jumpPage('lotteryDesc')"
          src="/image/lottery-v3/desc1-icon.svg"
        />
        <!-- 奖池 -->
        <Jackpot
          class="lottery-jackpot"
          :source="pool"
          :moneyEnd="moneyEnd"
          :moneyStart="moneyStart"
        ></Jackpot>
        <!-- 手动关闭活动 -->
        <div
          v-if="lotteryStore.activityCurStatus == 0"
          class="content-bg"
          :class="{ 'content-bg-fri': lotteryStore.isFri }"
        >
          <WinningRecord></WinningRecord>
          <InviteFriendsView></InviteFriendsView>
          <WinningHistoryRecord></WinningHistoryRecord>
        </div>
        <!-- 已结束 -->
        <div
          v-if="lotteryStore.activityCurStatus == 5"
          class="content-bg"
          :class="{ 'content-bg-fri': lotteryStore.isFri }"
        >
          <winningResult :source="winningResultInfo"></winningResult>
        </div>
        <!-- 我的下注记录,往期抽奖 -->
        <div class="record items-center">
          <!-- 中奖记录 -->
          <div
            v-if="Number(lotteryStore.activityCurStatus) == 5"
            class="record-item items-center"
            :class="{
              'record-item-fri': lotteryStore.isFri,
            }"
            @click="jumpPage('winDetails')"
          >
            <img
              v-if="!lotteryStore.isFri"
              class="record-item-icon"
              src="/image/lottery-v3/winDetails-icon.svg"
            />
            <img
              v-else
              class="record-item-icon"
              src="/image/lottery-v3/winDetails1-icon.svg"
            />
            <div class="record-item-text">
              {{ $t("lotteryMoney.zjjl") }}
            </div>
          </div>

          <!-- 下注记录 -->
          <div
            v-if="Number(lotteryStore.activityCurStatus) == 5"
            class="record-item items-center"
            :class="{
              'record-item-fri': lotteryStore.isFri,
            }"
            @click="jumpPage('dayBettingRecord')"
          >
            <img
              v-if="!lotteryStore.isFri"
              class="record-item-icon"
              src="/image/lottery-v3/bettingRecord-icon.svg"
            />
            <img
              v-else
              class="record-item-icon"
              src="/image/lottery-v3/bettingRecord1-icon.svg"
            />
            <div class="record-item-text">
              {{ $t("lotteryMoney.blxzjl") }}
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>
<script setup name="lotteryV3">
import { getJackpotSessionInfo, syncServerTime } from "@/api/lottery";
import { useGlobalStore } from "~~/store/global";
import { useLotteryV3Store } from "~~/store/modules/lottery-v3";
import { useDateFormat } from "@vueuse/core";
import Jackpot from "@/components/lottery-v3/jackpot.vue";

// 中奖记录
const WinningRecord = defineAsyncComponent(() =>
  import("@/components/lottery-v3/winning-record.vue")
);

// 邀友模块
const InviteFriendsView = defineAsyncComponent(() =>
  import("@/components/lottery-v3/invite-friends-view.vue")
);

// 历史中奖
const WinningHistoryRecord = defineAsyncComponent(() =>
  import("@/components/lottery-v3/winning-history-record.vue")
);

// 中奖结果
const winningResult = defineAsyncComponent(() =>
  import("@/components/lottery-v3/winning-result.vue")
);

/**
 * @description:  页面逻辑如下
 * 1. 在socket 建立之前,先获取一次需要的信息
 * 2. socket 成功建立在更新一次所有信息;在追加新的消息
 * 3. 页面销毁,关闭 socket
 * 4.
 *
 * @author: zhj1214
 */

const route = useRoute();
console.log("页面参数:", route.query);

const globalStore = useGlobalStore();
// 如果没有登录-直接跳转登录页面
if (!globalStore.$state.token && process.client) {
  bridge.onAppLogin();
}

const lotteryStore = useLotteryV3Store();
// 翻译
const { t } = useI18n();
// firebase埋点
const firebase = useInitFirebase(); // 初始化firebase
// 导航
const scrollEl = ref();

// 抽奖信息
const lottery = ref();

/**
 * @description: 查询抽奖信息
 */
const moneyStart = ref(0); // 奖池起始金额
const moneyEnd = ref(0); // 奖池结束金额

const sessionStatus = ref(null); // 活动状态(后端): 0:没有超级抽奖(特殊场景,手动关闭抽奖) 1:未开始 2:进行中 3:已结束(抽奖结果生成中) 5:已结束(抽奖结果已生成)
const pool = ref(null); // 奖池数据
// 是否正在请求
let isRequestLotteryInfo = false;
// 结算完成信息
const winningResultInfo = ref();
const getJackpotSessionInfoRequest = async (isLoading = false) => {
  isRequestLotteryInfo = true;
  // 1. 是否需要 loadding
  if (isLoading) {
    showLoadingToast({
      message: `${t("common.requestIng")}...`,
      forbidClick: true,
      duration: 15000,
    });
  }
  // 2. 请求

  let res = await getJackpotSessionInfo({
    sessionId: route.query.sessionId,
    querySourceType: 2,
  });

  console.log("页面信息:", res);
  /******** start zhjdebugger start ********/
  // res.beginTime = Date.now() + 15 * 1000;
  // res.beginTime = Date.now() + 15 * 1000;
  // res = null;
  // res.superPool = null;
  // 周5
  // res.periodId = res.sessionId;
  // res.sessionStatus = 5;

  /******** end zhjdebugger end ********/
  if (res) {
    // 打印
    console.warn(
      "活动开始时间:",
      useDateFormat(Number(res.sessionTime), "YYYY-MM-DD HH:mm:ss").value
    );

    // 2. 赋值
    sessionStatus.value = res.sessionStatus;
    lotteryStore.$patch((state) => {
      state.sessionStatus = res.sessionStatus;
      state.beginTime = res.sessionTime;
      state.sessionId = res.sessionId;
      state.periodId = res.periodId;
      state.jackpotType = res.jackpotType;
    });
    if (res.sessionResult) winningResultInfo.value = res.sessionResult;
    // 2.1
    let lotteryInfo = {
      sessionId: res.sessionId,
      periodId: res.periodId,
      beginTime: res.beginTime,
    };

    // 4. 奖池数据
    if (res.jackpotPoolAmount) {
      pool.value = {
        jackpotPoolAmount: res.jackpotPoolAmount,
        isReachMax: res.reachMaxBdcIncrementAmountLimit,
        maxBdcIncrementAmount: res.maxBdcIncrementAmount,
      };

      // 4.1 奖池滚动
      if (moneyStart.value == 0 && moneyEnd.value == 0) {
        moneyStart.value = Number(decimalToLength(res.jackpotPoolAmount));
        moneyEnd.value = Number(decimalToLength(res.jackpotPoolAmount));
      } else if (Number(res.jackpotPoolAmount) > moneyEnd.value) {
        moneyEnd.value = Number(decimalToLength(res.jackpotPoolAmount));
        setTimeout(() => {
          moneyStart.value = Number(decimalToLength(res.jackpotPoolAmount));
        }, 500);
      } else {
        moneyEnd.value = Number(decimalToLength(res.jackpotPoolAmount));
      }
    } else {
      moneyEnd.value = 0;
      moneyStart.value = 0;
      pool.value = {
        jackpotPoolAmount: 0,
        isReachMax: 0,
        maxBdcIncrementAmount: 1000,
      };
    }

    lottery.value = lotteryInfo;
  } else {
    lottery.value = {
      sessionId: 4,
    };
    pool.value = { lotteryPoolAmount: 0 };
    sessionStatus.value = 4;
    lotteryStore.$patch((state) => {
      state.sessionStatus = 4;
    });
  }
  // 重置状态
  isRequestLotteryInfo = false;
  return Promise.resolve();
};

/**
 * @description: 同步服务器时间
 */
const ckbzTime = new Date("2024/01/01").getTime(); // 创建一个特定时间的 Date 对象; 用于解决serverTime 初始值小于 1000 的场景
const serverTime = ref(ckbzTime);
const syncServerTimeFn = async () => {
  const res = await syncServerTime();
  if (res && res.nowMilli) {
    // 1. 是否更新时间
    if (Number(res.nowMilli) > Number(serverTime.value)) {
      serverTime.value = Number(res.nowMilli);
    }
  }
};

onMounted(async () => {
  // 1. 埋点
  firebase?.logEvent("BDC_H5_Lottery_V3_previous_detail_PUV");
  // 2.获取服务时间,并初始化数据
  syncServerTimeFn().then(() => {
    // 2.2 获取抽奖信息
    getJackpotSessionInfoRequest(true);
  });
});

onBeforeUnmount(() => {});

/****************** start 页面跳转 start ******************/
const jumpPage = async (type, isApp = false) => {
  if (type === "lotteryDesc") {
    firebase?.logEvent("BDC_H5_Lotteryv3_Desc_PUV"); // 埋点访问
    await navigateI18nTo({ path: "/lottery-v3/desc" });
  } else if (type === "bdcToMoney") {
    firebase?.logEvent("BDC_H5_Lotteryv3_BDCToMoney_Click"); // 埋点访问
    await navigateI18nTo({ path: "/lottery-v3/bdc-to-money" });
  } else if (type == "winDetails") {
    if (!route.query.sessionId) return;
    navigateI18nTo({
      path: "/lottery-v3/day-winning-details",
      query: {
        sessionId: route.query.sessionId,
      },
    });
  } else if (type == "dayBettingRecord") {
    firebase?.logEvent("BDC_H5_dayBettingRecord_PUV");
    navigateI18nTo({
      path: "/lottery-v3/day-betting-record",
      query: {
        sessionId: lottery.value.sessionId,
      },
    });
  }
};
/**
 * @description: 返回上一级
 */
const handleBack = () => {
  if (!window.history.state.back) {
    navigateI18nTo({
      path: "/activity",
    });
  } else {
    navigateBack(-1);
  }
};
</script>
<style lang="scss" scoped>
.lottery {
  position: relative;
  height: 100vh;
  overflow-y: scroll;
  overflow-x: hidden;
  will-change: scroll-position;
  padding-bottom: calc(var(--safe-area-inset-bottom) + 60 * 2px);
  background: #e5f2ff;
  &-fri {
    background: #fdf4dd !important;
  }
  &-bg {
    position: absolute;
    top: 0;
    left: 0px;
    width: 100vw;
    height: 366 * 2px;
    background: linear-gradient(180deg, #1a88ff 0%, #98dcff 40%, #98dcff 100%);
    
    &-end {
      height: 305 * 2px;
      background: linear-gradient(180deg, #3a99ff 0%, #daf3ff 100%);
    }
    &-fri {
      background: linear-gradient(
        180deg,
        #fda82b 0%,
        #ffe49e 40%,
        #ffe49e 100%
      ) !important;
    }
  }

  &-wait {
    position: relative;
    padding: 6 * 2px 15 * 2px;
    z-index: 9;
    background: rgba(0, 123, 255, 0.3);
    backdrop-filter: blur(12px);
    justify-content: space-between;
    &-sun {
      background: rgba(204, 122, 0, 0.3);
    }
    &-icon {
      width: 16 * 2px;
      height: 16 * 2px;
      margin-right: 4 * 2px;
    }
    &-text {
      color: #fff;
      font-size: 13 * 2px;
      &-sun {
        color: #fff;
      }
    }
    &-btn {
      width: 22 * 2px;
      height: 22 * 2px;
    }
  }

  // 兑换入口
  &-redemption {
    position: absolute;
    z-index: 9;
    top: -25 * 2px;
    left: 15 * 2px;
    width: 30 * 2px;
    height: 30 * 2px;
  }

  // 说明入口
  &-desc {
    position: absolute;
    z-index: 9;
    top: -25 * 2px;
    right: 15 * 2px;
    width: 30 * 2px;
    height: 30 * 2px;
  }
  // 奖池
  &-jackpot {
    margin-top: 30 * 2px;
    margin-bottom: 0;
  }
}

.content {
  position: relative;
  &-bg {
    // background: linear-gradient(180deg, #E5F2FF 0%, #E5F2FF 100%);
    background: #e5f2ff;
    padding-top: 15 * 2px;
    margin-top: -5 * 2px;
    &-fri {
      background: #fdf4dd;
    }
  }
}
.record {
  background-color: #fff;
  justify-content: space-between;
  padding: 10 * 2px;
  margin: 0 15 * 2px;
  border-radius: 12 * 2px;
  margin-bottom: 10 * 2px;
  &-item {
    flex-direction: column;
    justify-content: center;
    padding: 4 * 2px;
    border-radius: 4 * 2px;
    background: #f2f8ff;
    width: 159 * 2px;
    &-fri {
      background: #fffaf2;
    }
    &-icon {
      width: 24 * 2px;
      height: 24 * 2px;
      margin-bottom: 4 * 2px;
    }
    &-text {
      color: #141924;
      text-align: center;
      font-size: 12 * 2px;
    }
  }
}
</style>
